﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using System.Xml.Serialization;

namespace WebLib.AuthorizeService
{
    public class MemberInfo
    {
        private static MemberInfo _instance;

        protected MemberInfo()
        {
            var req = HttpContext.Current.Request;

            if (req.Cookies.Count > 0 && req.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                var cookie = req.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    var str = cookie.Value;

                    var userIdentity = GetUserData(str);

                    IsSignIn = true;
                    UserKey = userIdentity.UserKey;
                    UserID = userIdentity.UserId;
                    UserName = userIdentity.UserName;
                    UserRole = userIdentity.UserRoles;
                }
            }
        }

        public static MemberInfo Instance
        {
            get
            {
                //if (_instance == null)
                //{
                    _instance = new MemberInfo();
                //}

                return _instance;
            }
            set
            {
                _instance = value;
            }
        }

        public int UserKey { get; private set; }

        public string UserID { get; private set; }

        public string UserName { get; private set; }

        public bool IsSignIn { get; private set; }

        private string[] _userRole;
        public string[] UserRole
        {
            get
            {
                if (_userRole == null)
                    return (_userRole = new string[0]);
                return _userRole;
            }
            set
            {
                _userRole = value;
            }
        }

        private static UserDataModel GetUserData(string str)
        {
            var ticket = FormsAuthentication.Decrypt(str);
            var xs = new XmlSerializer(typeof(UserDataModel));

            if (ticket == null) return null;

            var sr = new StringReader(ticket.UserData);
            return (UserDataModel)xs.Deserialize(sr);
        }
    }
}
